/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jack.utils;

import com.jack.CounterItem;
import java.io.IOException;
import javax.microedition.rms.*;

/**
 *
 * @author jack
 */
public class RMSUtil {

    public static boolean recordStoreExists(String recordStoreName) {
        boolean existingOrNot = false;
        RecordStore rs = null;
        if (recordStoreName == null
                || recordStoreName.equals("")
                || recordStoreName.length() > 32) {
            return false;
        }
        try {
            rs = RecordStore.openRecordStore(recordStoreName, false);
        } catch (RecordStoreNotFoundException e) {
            existingOrNot = false;
        } catch (Exception e) {
        } finally {
            try {
                rs.closeRecordStore();
            } catch (Exception e) {
            }
        }
        return existingOrNot;
    }

    public static RecordEnumeration getRecordEnum(RecordStore recordStore)
            throws RecordStoreNotOpenException {
        RecordEnumeration rerecordEnum = recordStore.enumerateRecords(null, new RecordComparator() {
            public int compare(byte[] data1, byte[] data2) {
                int result = 0;
                try {
                    CounterItem item1 = new CounterItem(data1);
                    CounterItem item2 = new CounterItem(data2);
                    if (item1.getSequence() > item2.getSequence()) {
                        //>
                        result = RecordComparator.FOLLOWS;
                    } else if (item1.getSequence() == item2.getSequence()) {
                        //==
                        result = RecordComparator.EQUIVALENT;
                    } else {
                        //<
                        result = RecordComparator.PRECEDES;
                    }
                } catch (IOException e) {
                    return RecordComparator.PRECEDES;
                }

                return result;
            }
        }, false);

        return rerecordEnum;
    }
}
